const { startProcess, qiniuUpload } = require('../libs/utils');
const config = require('../config/config');
const qiniuConf = config.qiniu;

const { addSliderData } = require('../services/Slider');
const { addAgencyInfoData } = require('../services/AgencyInfo');
const { addRecomCourseData } = require('../services/RecomCourse');
const { addCourseCollectionData } = require('../services/CourseCollection');
const { addTeacherData } = require('../services/Teacher');
const { addStudentData } = require('../services/Student');
const { addCourseTabData } = require('../services/CourseTab');
const { addTotalCourseData } = require('../services/Course');
const { addAboutUsData } = require('../services/AboutUs');

const { CRAWLER } = require('../config/error_config')
const { returnInfo } = require('../libs/utils');
class Crawler {

  async crawlAction (ctx, next) {
    const { apiName } = ctx.request.body;
    const result = await Crawler.prototype[apiName](ctx, next);
    ctx.body = result;
  }

  async crawlSliderData (ctx, next) {
    return new Promise(resolve => {
       //函数 功能-调用子进程
      startProcess({
        file: 'slider', //默认配置到controllers/crawlers/目录底下      
        async message(data) {
          //上传到七牛云
          data.map(async item => {
            if (item.imgUrl && !item.imgKey) {
              
              try {
                const imgData = await qiniuUpload({
                  url: item.imgUrl,
                  bucket: qiniuConf.bucket.tximg.bucket_name,
                  ext: '.jpg'
                });

                if (imgData.key) {
                  item.imgKey = imgData.key;
                }

                const result = addSliderData(item);
                //each itemData in the db
                //每项数据插入数据库
                if (result) {
                  console.log('data create ok!');
                } else {
                  console.log('data create faild')
                }
              } catch (err) {
                console.log('发生错误');
                // console.log(err);
              }
            }
          });
          //返回结果
          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS))
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        }
      })
    })
   
  }

  async crawlAgencyInfo() {
    return new Promise(resolve => {
      //调用子进程
      startProcess({
        file: 'agencyInfo',  //默认配置到controllers/crawlers/目录底下o',
        async message(data) {
          if (data.logoUrl && !data.logoKey) {

            //保存到七牛云
            try {
              //七牛上传 qiniu upload
              const logoData = await qiniuUpload({
                url: data.logoUrl,
                bucket: qiniuConf.bucket.tximg.bucket_name,
                ext: '.jpg'
              });
              //添加上传后七牛云的图片key值 add qiniu img key
              if (logoData.key) {
                data.logoKey = logoData.key;
              }

              //把数据添加进数据库
              const result = await addAgencyInfoData(data);
              //each itemData in the db
              //每项数据插入数据库
              if (result) {
                console.log('data create ok!');
              } else {
                console.log('data create faild')
              }

            } catch (err) {
              console.log(err)
            }
          }

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED))
        }
      })
    })
  }

  async crawlRecomCourse() {
    return new Promise(resolve => {
      startProcess({
        file: 'recomCourse',  //默认配置到controllers/crawlers/目录底下se',
        async message(data) {
          //保存到七牛云
          data.map(async item => {
            try {
  
              if (item.teacherImgUrl && !item.teacherImgKey) {
                const imgData = await qiniuUpload({
                  url: item.teacherImgUrl,
                  bucket: qiniuConf.bucket.tximg.bucket_name,
                  ext: '.jpg'
                });
                //检查key
                if (imgData.key) {
                  item.teacherImgKey = imgData.key;
                }
              }
  
              if (item.posterUrl && !item.posterKey) {
                const imgData = await qiniuUpload({
                  url: item.posterUrl,
                  bucket: qiniuConf.bucket.tximg.bucket_name,
                  ext: '.jpg'
                });
                //检查key
                if (imgData.key) {
                  item.posterKey = imgData.key;
                }
              }
  
              const result = await addRecomCourseData(item);
              //each itemData in the db
              //每项数据插入数据库
              if (result) {
                console.log('data create ok!');
              } else {
                console.log('data create faild')
              }
  
            } catch (err) {
              console.log('发生错误');
              console.log(err);
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        }
      })
    })
  }
  //crawlRecomCourse end

  async crawlCourseCollection() {
    return new Promise(resolve => {
      startProcess({
        file: 'courseCollection',  //默认配置到controllers/crawlers/目录底下lection',
        async message(data) {
          //保存到七牛云
          data.map(async item => {
            //data里有三项推荐板块
            try {
  
              if (item.posterUrl && !item.posterKey) {
                const imgData = await qiniuUpload({
                  url: item.posterUrl,
                  bucket: qiniuConf.bucket.tximg.bucket_name,
                  ext: '.jpg'
                });
                //检查key
                if (imgData.key) {
                  item.posterKey = imgData.key;
                }
              }
              //保存进数据库
              const result = await addCourseCollectionData(item);
              //each itemData in the db
              //每项数据插入数据库
              if (result) {
                console.log('data create ok!');
              } else {
                console.log('data create faild')
              }
  
            } catch (err) {
              console.log('发生错误');
              console.log(err);
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        }
      });
    })
  }

  async crawlTeacher() {
    return new Promise( resolve => {
      startProcess({
        file: 'teacher',  //默认配置到controllers/crawlers/目录底下
        async message(data) {
          //保存到七牛云
          data.map(async item => {
            try {
              console.log(item);
  
              if (item.teacherImgUrl && !item.teacherImgKey) {
                const imgData = await qiniuUpload({
                  url: item.teacherImgUrl,
                  bucket: qiniuConf.bucket.tximg.bucket_name,
                  ext: '.jpg'
                });
                //检查key
                if (imgData.key) {
                  item.teacherImgKey = imgData.key;
                }
              }
              //保存进数据库
              const result = await addTeacherData(item);
              //each itemData in the db
              //每项数据插入数据库
              if (result) {
                console.log('data create ok!');
              } else {
                console.log('data create faild')
              }
  
            } catch (err) {
              console.log('发生错误');
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        }
      })
    })
  }
  //end

  async crawlStudent() {
    return new Promise( resolve => {
      startProcess({
        file: 'student',
        async message(data) {
          //保存到七牛云
          data.map(async item => {
            try {
  
              if (item.studentImgUrl && !item.studentImgKey) {
                const imgData = await qiniuUpload({
                  url: item.studentImgUrl,
                  bucket: qiniuConf.bucket.tximg.bucket_name,
                  ext: '.jpg'
                });
                //检查key
                if (imgData.key) {
                  item.studentImgKey = imgData.key;
                }
              }
  
              //保存进数据库
              const result = await addStudentData(item);
              //each itemData in the db
              //每项数据插入数据库
              if (result) {
                console.log('data create ok!');
              } else {
                console.log('data create faild')
              }
  
            } catch (err) {
              console.log('发生错误');
              // console.log(err);
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        }
      })
    })
  }
  //end

  async crawlCourseTab() {
    return new Promise( resolve => {
      startProcess({
        file: 'courseTab',  //修改
        async message(data) {
          //保存到七牛云
          data.map(async item => {
            //保存进数据库
            const result = await addCourseTabData(item);
            //each itemData in the db
            //每项数据插入数据库
            if (result) {
              console.log('data create ok!');
            } else {
              console.log('data create faild')
            }
  
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        }
      })
    })
  }
  //end

  async crawlTotalCourse() {
    return new Promise( resolve => {
      startProcess({
        file: 'totalCourse',  //修改
        async message(data) {
  
          data.map(async item => {
            try {
  
              if (item.posterImgUrl && !item.posterImgKey) {
                const imgData = await qiniuUpload({
                  url: item.posterImgUrl,
                  bucket: qiniuConf.bucket.tximg.bucket_name,
                  ext: '.jpg'
                });
                //检查key
                if (imgData.key) {
                  item.posterImgKey = imgData.key;
                }
              }
  
              //保存进数据库
              const result = await addTotalCourseData(item);
              //each itemData in the db
              //每项数据插入数据库
              if (result) {
                console.log('data create ok!');
              } else {
                console.log('data create faild')
              } 
  
            } catch (err) {
              console.log('发生错误');
              // console.log(err);
            }
          });
          
          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        }
      })
    })
  }
  //end

  async crawlAboutUs() {
    return new Promise( resolve => {
      startProcess({
        file: 'aboutUs',  //修改
        async message(data) {
          try {
            if (data.posterImgUrl && !data.posterImgKey) {
              const imgData = await qiniuUpload({
                url: data.posterImgUrl,
                bucket: qiniuConf.bucket.tximg.bucket_name,
                ext: '.jpg'
              });
              //检查key
              if (imgData.key) {
                data.posterImgKey = imgData.key;
              }
            }

            //保存进数据库
            const result = await addAboutUsData(data);
            //each itemData in the db
            //每项数据插入数据库
            if (result) {
              console.log('data create ok!');
            } else {
              console.log('data create faild')
            } 

          } catch (err) {
            console.log('发生错误');
            console.log(err);
          }
  
          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          //console.log(code);
        },
        async error(err) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        }
      })
    })
  }
  //end
}

module.exports = new Crawler();